package com.kunya.product.interceptor;

import com.kunya.common.util.RedisPoolUtil;
import com.kunya.product.util.ReflectUtil;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.sql.Connection;
import java.util.Properties;

/**
 * @author zp
 * @Description:
 * @date 2018/5/29 16:51
 */
@Intercepts({@Signature(type=StatementHandler.class,method="prepare",args={Connection.class})})
public class PrefixInteceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //是通过Interceptor的plugin方法进行包裹的，所以我们这里拦截到的目标对象肯定是RoutingStatementHandler对象。
        if(invocation.getTarget() instanceof RoutingStatementHandler){
            RoutingStatementHandler statementHandler = (RoutingStatementHandler)invocation.getTarget();
            StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(statementHandler, "delegate");
            BoundSql boundSql = delegate.getBoundSql();
            //获取当前要执行的Sql语句，也就是我们直接在Mapper映射语句中写的Sql语句
            String sql =boundSql.getSql();
            sql=sql.substring(0,sql.indexOf("os_"));
            String newSql=sql.substring(0,sql.indexOf("os_"))+"prefix_"+sql.substring(sql.indexOf("os_"));
        }
        return invocation.proceed();
    }

    private String getTablePrefix(){
//        RedisPoolUtil.get()
        return null;
    }

    @Override
    public Object plugin(Object o) {
        return null;
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
